package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.*;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author zsk
 * @since 2022-04-11
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService apUserFollowService;

    //依赖注入kafka
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    /**
     * 登录验证
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        if (dto == null ||
                (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword())
                        && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断是否包含手机号和密码
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            //构建查询条件

            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone, dto.getPhone());

            //查询
            ApUser one = this.getOne(wrapper);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //获取用户盐
            String pwd = dto.getPassword() +one.getSalt();
            //使用md5加密
            String pass = DigestUtils.md5DigestAsHex(pwd.getBytes());

            //与数据库查询到的数据进行比对
            if (pass.equals(one.getPassword())) {
                //一致，生成token返回数据
                Map<String, Object> map = new HashMap<>();
                map.put("userId", one.getId());
                String token = AppJwtUtil.getToken(map);
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                //返回
                return ResponseResult.okResult(result);
            } else {
                //返回密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }

        //如果是游客登录，设备号不为空
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            //生成token
            Map<String, Object> map = new HashMap<>();
            map.put("userId", 0);//游客登录存入0
            String token = AppJwtUtil.getToken(map);
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);

            //返回
            return ResponseResult.okResult(result);
        }
        //其他情况返回null
        return null;
    }

    /**
     * 关注用户
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //获取当前登录用户id
        User user = AppThreadLocalUtil.get();
        if (user == null){
            //提示用户未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //构建对象
        ApUserFollow follow = new ApUserFollow();
        follow.setUserId(user.getUserId());//当前用户id
        //查询当前登录用户昵称
        ApUser apUser = this.getById(user.getUserId());
        follow.setUserName(apUser.getName());//当前登录用户昵称

        //关注作者id,远程Feign去调用
        ApAuthor apAuthor = null;
        ResponseResult<ApAuthor> result = articleFeign.findById(dto.getAuthorId());
        //取出参数
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            apAuthor= result.getData();
        }
        if (apAuthor !=null){
            follow.setFollowId(apAuthor.getUserId());//关注作者id
            follow.setFollowName(apAuthor.getName());//作者昵称
        }
        follow.setLevel(0);
        follow.setCreatedTime(new Date());

        //根据id查询记录
        LambdaUpdateWrapper<ApUserFollow> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ApUserFollow::getUserId,user.getUserId());

        wrapper.eq(ApUserFollow::getFollowId,apAuthor.getUserId());
        //判断前端传递行为
        if (dto.getOperation() == 0){
            //需要先查询数据库中是否有这条记录

            ApUserFollow one = apUserFollowService.getOne(wrapper);
            if (one == null){
                //新增数据
                apUserFollowService.save(follow);
            }
        }else {
            //否则，删除该记录
            apUserFollowService.remove(wrapper);
        }

        //将此行为发送到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setFollowId(apAuthor.getUserId());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setOperation(dto.getOperation());

        //发送消息
        String json = JSON.toJSONString(followBehaviorDto);

        kafkaTemplate.send(followBehaviorTopic,json);


        //返回结果
        return ResponseResult.okResult();
    }

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
